<template>
  <div class="note-space-wrapper">
    <div
      class="note-space-header"
      style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 6px;
      "
    >
      <h1>笔记空间</h1>
      <div style="margin-right: 20px">
        <Message />
      </div>
    </div>
    <div class="tabs-wrapper">
      <el-tabs
        v-model="activeTab"
        class="demo-tabs"
        @tab-change="handleChangeTab"
      >
        <el-tab-pane
          v-for="item in tabs"
          :key="item.id"
          :label="item.label"
          :name="item.name"
        >
        </el-tab-pane>
      </el-tabs>
      <el-segmented
        v-show="activeTab === enumNoteType.publish"
        v-model="segmentActive"
        :options="options"
        @change="handleChangeSegment"
        size="default"
      />
      <div class="note-list-wrapper" v-loading="loading">
        <div class="note-content">
          <div
            width="100%"
            shadow="hover"
            v-for="(item, index) in noteList"
            :key="index"
            style="position: relative; width: 100%"
            class="note-item-li item-box"
            @click.stop="handleJumpToNoteDetail(item, e)"
          >
            <div
              class="delete-note"
              v-if="segmentActive === enumNoteType.publish"
              @click="handleDeleteNote(item)"
            >
              <el-icon><Delete /></el-icon>
            </div>
            <div
              class="item-header"
              style="
                font-size: 14px;
                display: flex;
                gap: 10px;
                align-items: center;
              "
            >
              <el-text
                style="width: 200px; height: 20px; font-weight: 600"
                truncated
              >
                {{ item.title }}
              </el-text>
              <span
                v-if="
                  activeTab === enumNoteType.publish &&
                  segmentActive === enumNoteType.publish
                "
              >
                {{ new Date(item.publish_at).toLocaleString() }}</span
              >
              <span style="color: #aaa; font-size: 12px" v-else>
                {{ formatTime(new Date(item.publish_at).getTime()) }}，来自{{
                  item.user_name
                }}的分享</span
              >
            </div>
            <div
              class="item-content"
              style="
                display: flex;
                justify-content: space-between;
                height: 48px;
              "
            >
              <div
                v-if="item.note_content && item.icon == 'Document'"
                class="content-w"
                :style="{
                  width: segmentActive === enumNoteType.publish ? '80%' : '98%',
                }"
              >
                <el-text
                  :innerHTML="removeImgFromHtml(item.note_content)"
                  line-clamp="2"
                  style="width: 100%; height: 48px"
                >
                </el-text>
              </div>
              <div
                v-else-if="item.icon == 'FlowChart'"
                style="
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <!-- <el-icon style="font-size: 44px" color="#409eff">
                  <FlowChart />
                </el-icon> -->
                <el-text> 这是一篇流程图笔记 </el-text>
              </div>
              <div
                v-else-if="item.icon == 'Xmind'"
                style="
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <!-- <el-icon style="font-size: 44px" color="#409eff">
                  <Xmind />
                </el-icon> -->
                <el-text> 这是一篇思维导图笔记 </el-text>
              </div>
              <!-- <div
                v-else
                style="cursor: pointer"
                :style="{
                  width: segmentActive === enumNoteType.publish ? '80%' : '98%',
                }"
              >
                <el-text
                  style="width: 100%"
                  :innerHTML="removeImgFromHtml(item.note_content)"
                  line-clamp="1"
                >
                </el-text>
              </div> -->
              <div
                class="proccess-status"
                style="display: flex; justify-content: center"
                v-if="segmentActive === enumNoteType.publish"
              >
                <el-icon
                  size="48"
                  v-if="item.status === enumProccessTypeValue.Pass"
                  ><ProcessSuccess />
                </el-icon>
                <el-icon
                  size="48"
                  v-else-if="
                    item.status === enumProccessTypeValue.Force ||
                    item.status === enumProccessTypeValue.Fail
                  "
                >
                  <ProcessFail
                /></el-icon>
                <el-icon
                  size="48"
                  v-else-if="item.status === enumProccessTypeValue.Processing"
                >
                  <Processing
                /></el-icon>
              </div>
            </div>
            <!-- 交互区域 -->
            <div
              class="item-footer"
              style="
                display: flex;
                gap: 40px;
                align-items: center;
                font-size: 12px;
                margin-top: 10px;
              "
            >
              <div
                style="
                  cursor: pointer;
                  display: flex;
                  align-items: center;
                  gap: 4px;
                "
                v-if="item.status === enumProccessTypeValue.Pass"
                @click.stop="handleClick(item, 1)"
              >
                <el-icon
                  size="20"
                  :style="{
                    color: item.is_praise ? '#ff5a5a' : '',
                  }"
                >
                  <AwesomeFilled />
                </el-icon>
                <span> {{ item.praise_num }}</span>
              </div>
              <div
                style="
                  cursor: pointer;
                  display: flex;
                  align-items: center;
                  gap: 4px;
                "
                v-if="item.status === enumProccessTypeValue.Pass"
                @click.stop="handleClick(item, 2)"
              >
                <el-icon size="20">
                  <ChatDotRound />
                </el-icon>
                <span>{{ item.comment_reply_sum }}条评论</span>
              </div>
              <div
                style="
                  cursor: pointer;
                  display: flex;
                  align-items: center;
                  gap: 4px;
                "
                @click.stop="handleClick(item, 3)"
                v-if="!(segmentActive === 2 && activeTab === 2)"
              >
                <el-icon
                  size="20"
                  :style="{
                    color: item.is_collect ? '#fcb510' : '',
                  }"
                >
                  <StarFilled v-if="item.is_collect" />
                  <Star v-else />
                </el-icon>
                <span>收藏</span>
              </div>
              <div
                style="
                  cursor: pointer;
                  display: flex;
                  align-items: center;
                  gap: 4px;
                "
                v-if="segmentActive === 2 && activeTab === 2"
              >
                <el-icon size="20">
                  <View />
                </el-icon>
                <span>{{ item.view_num }}</span>
              </div>
              <el-popover
                placement="bottom-start"
                :width="800"
                trigger="click"
                popper-class="custom-popover-note-space"
                v-if="segmentActive !== 2 || activeTab !== 2"
              >
                <p
                  style="
                    color: var(--el-color-danger);
                    padding: 10px 0;
                    text-align: center;
                  "
                >
                  我们会快速处理您的投诉意见、请尽量提交详细的投诉说明
                </p>
                <el-form
                  :ref="
                    (ref) => {
                      mapRef[item.id] = ref
                    }
                  "
                  style="max-width: 800px"
                  :model="ruleForm"
                  :rules="rules"
                  label-width="100px"
                  class="demo-ruleForm"
                  :size="formSize"
                  status-icon
                >
                  <el-form-item label="投诉类型" prop="complaintSelectedTypes">
                    <el-checkbox-group
                      v-model="ruleForm.complaintSelectedTypes"
                      style="display: flex; gap: 10px; flex-wrap: wrap"
                    >
                      <el-checkbox-button
                        v-for="type in complaintTypes"
                        :key="type"
                        :value="type"
                      >
                        {{ type }}
                      </el-checkbox-button>
                    </el-checkbox-group>
                  </el-form-item>
                  <el-form-item label="描述" prop="desc">
                    <el-input
                      show-word-limit
                      v-model="ruleForm.desc"
                      maxlength="300"
                      type="textarea"
                      resize="none"
                    />
                  </el-form-item>
                  <el-form-item label="投诉截图" prop="images">
                    <ImageShow
                      v-model:list="ruleForm.images"
                      :limit="3"
                      :showDrag="false"
                      :multiple="false"
                      image-size="100px"
                    ></ImageShow>
                  </el-form-item>
                  <div
                    style="
                      display: flex;
                      justify-content: flex-end;
                      width: 100%;
                    "
                  >
                    <el-button
                      type="primary"
                      :loading="complaintLoading"
                      @click="submitForm(item.id)"
                    >
                      确定
                    </el-button>
                    <el-button @click.prevent.stop="handleCancel(item.id)">
                      取消
                    </el-button>
                  </div>
                </el-form>
                <template #reference>
                  <div
                    style="
                      cursor: pointer;
                      display: flex;
                      align-items: center;
                      gap: 4px;
                    "
                    @click.stop="handleClick(item, 4)"
                  >
                    <el-icon size="20">
                      <Component :is="Flag" />
                    </el-icon>
                    <span>举报</span>
                  </div>
                </template>
              </el-popover>
            </div>
            <div
              class="comment-area"
              style="margin-top: 4px; max-width: 600px"
              v-if="item.showComment"
            >
              <Comment
                @click.stop="() => {}"
                v-model:comment-total="item.comment_num"
                :sourceId="item.id"
              />
            </div>
            <div
              class="mask"
              v-if="enumProccessTypeValue.Force === item.status"
              style="
                display: flex;
                align-items: center;
                gap: 20px;
                padding: 20px;
              "
            >
              <div class="left" style="display: flex; flex-direction: column">
                <el-icon style="color: red" size="36"
                  ><WarningFilled
                /></el-icon>
                <span style="color: red">强制下架</span>
              </div>
              <div class="right" style="color: #000; font-weight: 600">
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="item.failed_reason"
                  placement="top-start"
                >
                  <el-text style="width: 100%" line-clamp="3">
                    {{ item.failed_reason }}
                  </el-text>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-empty description="暂无数据" v-if="!loading && !noteList.length" />
      <Pagination
        v-if="noteList.length"
        :total="noteListTotal"
        v-model:page="queryNote.page"
        v-model:limit="queryNote.limit"
        @pagination="getList"
      />
    </div>
  </div>
  <div v-show="false" ref="closeRef"></div>
</template>
<script setup>
import { ref, reactive, nextTick } from 'vue'
import AwesomeFilled from '@/icons/Awesome.vue'
import StarFilled from '@/icons/StarFilled.vue'
import ProcessFail from '@/icons/ProcessFail.vue'
import Processing from '@/icons/Processing.vue'
import ProcessSuccess from '@/icons/ProcessSuccess.vue'
import Awesome from '@/icons/Awesome.vue'
import { Flag, ChatDotRound, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/pagination/index.vue'
import { useRouter } from 'vue-router'
import Message from './Message.vue'
import {
  debounce,
  replaceImg,
  removeImgFromHtml,
  formatTime,
} from '@/utils/tools.ts'
import Comment from '@/components/comment/index.vue'
import ImageShow from '@/components/image-show/index.vue'
import {
  httpGetNoteSpaceListWithDiffType,
  httpCollectNoteFromNoteSpace,
  httpPraiseNoteFromNoteSpace,
  httpUnpublishFromNoteSpace,
  httpGetComplaintTypes,
  httpComplaintNote,
} from '@/api/note.js'
import { enumNoteType, enumProccessTypeValue } from '@/enum/note'
import useNoteStore from '@/stores/note'
import { storeToRefs } from 'pinia'
const noteState = useNoteStore()
const { noReadNum } = storeToRefs(noteState)

const router = useRouter()
const activeTab = ref(0)
const segmentActive = ref(0)
const complaintTypes = ref([])
const showPopoverVisible = ref(false)
const options = [
  {
    label: '我的发布',
    value: enumNoteType.publish,
  },
  {
    label: '我的收藏',
    value: enumNoteType.collect,
  },
  {
    label: '我赞过的',
    value: enumNoteType.like,
  },
]
const tabs = [
  {
    id: 1,
    label: '最新',
    name: 0,
  },
  {
    id: 2,
    label: '热门',
    name: 1,
  },
  {
    id: 3,
    label: '我的',
    name: 2,
  },
]
const formSize = ref('default')
const mapRef = ref({})
const rules = {
  complaintSelectedTypes: [
    {
      required: true,
      message: '请选择投诉类型',
      trigger: 'blur',
    },
  ],
}
const ruleForm = reactive({
  desc: '',
  complaintSelectedTypes: [],
  images: [],
})
const handleChangeTab = (item) => {
  queryNote.q_type = item
  if (item === 2) {
    segmentActive.value = 2
  }
  queryNote.page = 1
  noteList.value = 0
  noteListTotal.value = 0
  getList()
}
const handleChangeSegment = (item) => {
  queryNote.q_type = segmentActive.value
  queryNote.page = 1
  noteList.value = 0
  noteListTotal.value = 0
  getList()
}
const clickNodeId = ref()
const handleJumpToNoteDetail = (item, e) => {
  if (item.status === enumProccessTypeValue.Force) return
  router.push('/file/note-detail/' + item.id)
}
const handleClick = debounce(async (item, id) => {
  clickNodeId.value = item.id
  switch (id) {
    case 1:
      // 点赞
      const res = await httpPraiseNoteFromNoteSpace({ id: item.id })
      if (res) {
        item.is_praise = !item.is_praise
        item.praise_num = item.is_praise
          ? item.praise_num + 1
          : item.praise_num - 1
      }
      return
    case 2:
      // 评论
      item.showComment = !item.showComment
      return
    case 3:
      // 收藏
      const resp = await httpCollectNoteFromNoteSpace({ id: item.id })
      if (resp) {
        item.is_collect = !item.is_collect
      }
      return item.is_collect ? 'orange' : ''
    case 4:
      // 投诉
      showPopoverVisible.value = item.id
      ruleForm.complaintSelectedTypes = []
      ruleForm.images = []
      ruleForm.desc = ''

      return item.isFlag ? 'orange' : ''
    default:
      return ''
  }
}, 300)

const queryNote = reactive({
  page: 1,
  limit: 20,
  status: 0,
  q_type: 0, // 类型：0最新，1热门，2我发布的，3我的收藏，4我赞过，5我评论过
})
const loading = ref(false)
const noteListTotal = ref(200)
const noteList = ref([])
const getList = async () => {
  loading.value = true
  noteList.value = []
  noteListTotal.value = 0
  let data = {
    ...queryNote,
  }
  const response = await httpGetNoteSpaceListWithDiffType(data).catch(
    () => null,
  )
  loading.value = false
  if (!response) return
  const { list, total } = response
  noteList.value = list
  noteListTotal.value = total
}
/**
 * 投诉类型列表
 */
const getComplainList = async () => {
  const result = await httpGetComplaintTypes()
  if (result.list.length) {
    complaintTypes.value = result.list
  }
}
getList()
getComplainList()
const handleDeleteNote = (item) => {
  ElMessageBox.confirm('取消发布笔记', '确认取消发布到笔记空间吗?', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await httpUnpublishFromNoteSpace({
        note_space_id: item.id,
      })
      if (res) {
        getList()
        ElMessage.success('取消成功')
      } else {
        ElMessage.error('取消失败')
      }
    })
    .catch(() => {})
}
const closeRef = ref()
const handleCancel = (id) => {
  closeRef.value.click()
  resetForm(id)
}
const complaintLoading = ref(false)
const submitForm = async (id) => {
  let formEl = mapRef.value[id]
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let obj = {
        id,
        complaint_types: ruleForm.complaintSelectedTypes,
        complaint_input: ruleForm.desc,
        complaint_images: ruleForm.images,
      }
      complaintLoading.value = true
      const res = await httpComplaintNote({
        ...obj,
      })
      if (res) {
        ElMessage.success('举报成功')
        handleCancel(id)
      }
      complaintLoading.value = false
    } else {
      // console.log('error submit!', fields)
    }
  })
}

const resetForm = (id) => {
  let formEl = mapRef.value[id]
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style scoped lang="scss">
.note-space-wrapper {
  width: 100%;
  height: 100%;
  padding: 0 6px;
}
.note-list-wrapper {
  height: calc(100vh - 160px);
  padding-top: 14px;
  overflow-y: auto;
  // overflow-x: hidden;
  @include scrollBar;
  .note-content {
    display: flex;
    flex-direction: column;
    gap: 10px;

    .el-card {
      overflow: none !important;
    }
    .note-item-li {
      position: relative;
      .delete-note {
        position: absolute;
        top: -10px;
        right: 0;
        z-index: 99;
        cursor: pointer;
        &:hover {
          color: var(--el-color-danger);
        }
      }
      .mask {
        position: absolute;
        bottom: 0;
        top: 0;
        left: 0;
        right: 0;
        // background-color: var(--el-overlay-color-lighter);
        // background-color: var(--el-mask-color);
        background-color: rgba(255, 255, 255, 0.7);
        // background-color: var(--el-mask-color);
        overflow: hidden;
      }
    }
    .item-footer {
      span {
        i {
          &.primary {
            color: var(--el-color-primary) !important;
          }
          &.orange {
            color: var(--el-color-warning) !important;
          }
          &:hover {
            color: var(--el-color-primary) !important;
          }
        }
      }
    }
  }
  :deep(.el-card__body) {
    padding: 10px;
    position: relative;
  }
  .item-box {
    --el-card-border-color: var(--el-border-color-light);
    --el-card-border-radius: 4px;
    --el-card-padding: 20px;
    --el-card-bg-color: var(--el-fill-color-blank);
    background-color: var(--el-card-bg-color);
    border: 1px solid var(--el-card-border-color);
    border-radius: var(--el-card-border-radius);
    color: var(--el-text-color-primary);
    padding: 10px;
    transition: var(--el-transition-duration);
    &:hover {
      box-shadow: var(--el-box-shadow-light);
    }
  }
}
</style>
<style lang="scss">
.custom-popover-note-space {
  .el-checkbox-button__inner {
    border: var(--el-border) !important;
  }
}
</style>
